package com.cby.android.library.ext

import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData

/**
 * @description: LiveDataExt
 *
 * @author ChenBaoyang
 * @date 2021/12/4 11:10
 */
fun <T> MutableLiveData<T>.asLiveData(): LiveData<T> {
    return this
}

fun <T> MutableLiveData<T>.setState(reducer: T.() -> T) {
    this.value = this.value?.reducer()
}

fun <T> SingleLiveEvent<T>.setEvent(value: T) {
    this.value = value
}

fun <T> SingleLiveEvents<T>.setEvent(vararg values: T) {
    this.value = values.toList()
}

fun <T> LiveData<List<T>>.observeEvent(lifecycleOwner: LifecycleOwner, action: (T) -> Unit) {
    this.observe(lifecycleOwner) {
        it.forEach { event ->
            action.invoke(event)
        }
    }
}

fun <T, R> withState(state: LiveData<T>, block: (T) -> R): R? {
    return state.value?.let(block)
}